package com.sunday.common.netty.e5_Udp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class UdpClient1 {

    public static final String SERVER_HOST = "127.0.0.1";

    public static final int SERVER_PORT = 8822;

    public static void main(String[] args) {
        EventLoopGroup bossLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(bossLoopGroup)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.AUTO_CLOSE, true)
                    // ChannelOption.SO_BROADCAST 用于设置UDP广播模式。
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpClientChannel());

            ChannelFuture channelFuture = bootstrap.connect(SERVER_HOST, SERVER_PORT).sync();
            log.info("UDP client started.");

            log.info("Input message: ");

            while (true) {
                Scanner reader = new Scanner(System.in);
                String input = reader.nextLine();
                log.info("Input: {}", input);
                if ("quit".equalsIgnoreCase(input)) {
                    break;
                }
                ByteBuf byteBuf = Unpooled.copiedBuffer(input, CharsetUtil.UTF_8);
                channelFuture.channel().writeAndFlush(byteBuf);
            }

            channelFuture.channel().close();
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            bossLoopGroup.shutdownGracefully();
        }
    }

}
